#include "wav_to_text.h"

unsigned char *bmask(void)
{
  unsigned char *res = NULL;

  res = malloc(8 * sizeof(char));
  res[0] = 0x80;
  res[1] = 0x40;
  res[2] = 0x20;
  res[3] = 0x10;
  res[4] = 0x08;
  res[5] = 0x04;
  res[6] = 0x02;
  res[7] = 0x01;

  return (res);
}

/* Function use to find text hidding in the .wav (until stop mark or end of file) */
/* result : text file named result.txt */
/* generate : binary.txt (sound part of .wav) & header.txt (information part about .wav) */

void	answer(char *file)
{
  FILE *fhead, *fbin , *fres;
  int size = 0, i ;
  unsigned char *bm = NULL , var = 0 +'0';
  unsigned char letter = 0;

  text(file);
  fbin = fopen("binary.txt","r");
  fhead = fopen("header.txt", "r");
  size = header("header.txt");
  size = (size / 8) - 1;
  fres = fopen("result.txt", "w");
  bm = bmask();

  while ((letter != (0xFF)) && !(feof(fbin)) )
  {
    letter = 0;
    for ( i = 0; i <= 7; i++)
    {
      fseek(fbin , size , SEEK_CUR);
      fread(&var , sizeof (char) , 1, fbin);
      if (var & 0x01)
	letter = letter | bm[i];
    }
    if (letter != 0xFF)
    {
      fwrite(&letter, sizeof (char), 1, fres);
    }
  }
  free(bm);
  fclose(fhead);
  fclose(fbin);
  fclose(fres);
}
